<template>
	<view class="scan-camera">
		<camera class="camera-box" mode="scanCode" resolution="high" device-position="back" flash="auto"
			@error="userCancelCamera" @scancode="scanSuccess"></camera>

		<image class="scan-gif" v-show="isScanShow" src="https://biapi.vaubang.cn/UploadFiles/Images/scan.gif"
			mode="widthFix"></image>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isLoading: false,
				isScanShow: false,
			}
		},
		onLoad() {
			setTimeout(() => {
				this.isScanShow = true;
			}, 800)
		},
		methods: {
			// 用户不允许使用摄像头时触发
			userCancelCamera(e) {
				console.log('用户不允许使用摄像头时触发', e.detail);
			},
			// 在扫码识别成功时触发
			scanSuccess(e) {
				if (this.isLoading == false) {
					this.isLoading = true;
					this.scanBgmPlay(() => {
						setTimeout(() => {
							uni.vibrateLong();
							getApp().showLoading('识别中');
							console.log('在扫码识别成功时触发', e.detail);
							setTimeout(() => {
								uni.setStorageSync("couponPsw", e.detail.result);
								uni.hideLoading();
								uni.navigateBack();
							}, 1500)
						}, 300)
					});
				}
			},
			// 扫描成功播放扫描音频
			scanBgmPlay(cb) {
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src =
					'https://biapi.vaubang.cn/UploadFiles/Images/scan-bgm.mp3';
				innerAudioContext.onPlay(() => {
					console.log('开始播放');
					cb();
				});
				innerAudioContext.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
			},
		},
	}
</script>

<style lang="less">
	.scan-camera {
		.camera-box {
			position: fixed;
			top: 0;
			bottom: 0;
			left: 0;
			right: 0;
		}

		.scan-gif {
			width: calc(100% - 20px);
			position: fixed;
			left: 10px;
			right: 10px;
			top: 50%;
			margin-top: -50%;
		}
	}
</style>
